package com.xul.crowd.service.Impl;

import com.xul.crowd.entity.Auth;
import com.xul.crowd.entity.AuthExample;
import com.xul.crowd.mapper.AuthMapper;
import com.xul.crowd.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author xul
 * @create 2021-07-26 18:17
 */

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthMapper authMapper;

    /**
     * 查询所以的权限
     *
     * @return
     */
    @Override
    public List<Auth> getAllAuth() {
        return authMapper.selectByExample(new AuthExample());
    }

    /**
     * 根据中间表用roleId查询出所有的authId
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> getAssignedAuthIdByRoleId(Integer roleId) {
        List<Integer> authIdList = authMapper.selectAssignedAuthIdByRoleId(roleId);
        return authIdList;
    }

    /**
     * 将角色和权限关联的数据保存到数据库
     *
     * @param map
     */
    @Override
    public void saveRoleAuthRelationship(Map<String, List<Integer>> map) {
        // 1.获取到roleId的值
        List<Integer> roleList = map.get("roleId");
        Integer roleId = roleList.get(0);
        // 2.根据roleId删除旧的关联关系
        authMapper.deleteOldRelationship(roleId);
        // 3.获取到authList的值
        List<Integer> authList = map.get("authIdArray");
        // 4.判断authList的值是否有效 注意[]不是nul
        if (authList != null && authList.size() > 0) {
            // 5.将roleId和authList的关联数据保存到数据库
            authMapper.insertNewRelationship(roleId, authList);
        }
    }

    /**
     * 根据中间表用menuId查询出所有的authId
     *
     * @param menuId
     * @return
     */
    @Override
    public List<Integer> getAssignedAuthIdByMenuId(Integer menuId) {
        return authMapper.selectAssignedAuthIdByMenuId(menuId);
    }

    /**
     * 将菜单和权限关联的数据保存到数据库
     *
     * @param map
     */
    @Override
    public void saveMenuAuthRelationship(Map<String, List<Integer>> map) {
        List<Integer> menuList = map.get("menuId");
        Integer menuId = menuList.get(0);
        // 根据menuId删除旧的关联关系
        authMapper.deleteOldMenuRelation(menuId);
        List<Integer> authIdList = map.get("authIdArray");
        if (authIdList != null && authIdList.size() > 0) {
            // 将menuId和authIdList的关联数据保存到数据库
            authMapper.insertNewMenuRelation(menuId, authIdList);
        }
    }

    /**
     * 根据adminId查询到AuthName
     * @param adminId
     * @return
     */
    @Override
    public List<String> getAssignedAuthNameByAminId(Integer adminId) {
        return authMapper.selectAssignedAuthNameByAminId(adminId);
    }
}
